﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Reflection;
#if SILVERLIGHT
using System.Windows;
#endif
namespace SystemX.Web
{
	public static partial class ObjectX
	{
        /// <summary>
        /// Convert data a to an object using DataContractJsonSerializer serializer
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
		public static T DeserializeJSONStr1<T>(this string jsonStr) {
			Byte[] btypes = Encoding.Unicode.GetBytes(jsonStr);
			using (MemoryStream stream = new MemoryStream(btypes))
			{
				DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
				var retVal = (T)ser.ReadObject(stream);
				return retVal;
			}
		}
        /// <summary>
        /// Serializer a strong typed object to json string using JavaScriptSerializer
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
		public static string ToJSONStr1<T>(this T obj) {
			var retVal = string.Empty;
			using (MemoryStream stream = new MemoryStream())
			{
				DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
				ser.WriteObject(stream, obj);
				stream.Position = 0;
				using (StreamReader sr = new StreamReader(stream))
				{
					retVal = sr.ReadToEnd();
					return retVal;
				}
			}
		}
#if SILVERLIGHT
		public static object GetByKey(this ResourceDictionary dic,object key) {
			if (!dic.Contains(key)) return null;
			return dic[key];
		}
#endif
		public static T GetAssemblyAttribute<T>(this Assembly assembly) where T : Attribute
		{
			if (assembly == null) return null;
			object[] attributes = assembly.GetCustomAttributes(typeof(T), true);
			if (attributes == null) return null;
			if (attributes.Length == 0) return null;
			return (T)attributes[0];

		}
	}
}
